//
//  CCRViewController.m
//  iHealthEHR
//
//  Created by Joseph Ayo Akinyele on 3/12/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "CCRViewController.h"

// Descripton: pertains to loading Google Health specific CCR medical record
@implementation CCRViewController
@synthesize myProfileList;
@synthesize ccrProfiles, ccrNotices;
@synthesize curSelectedProfile;
@synthesize googlehealth;

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}


- (void)viewDidLoad {
	[self.navigationController setToolbarHidden:YES];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	[super viewDidLoad];
}

// Use to pull down record?
- (void)viewWillAppear:(BOOL)animated {
	[self.navigationController setToolbarHidden:YES];	
	// initialize the ccr profiles
	if(ccrProfiles == nil) {
		NSLog(@"Instantiating ccr profile dictionary.");
		ccrProfiles = [[NSMutableDictionary alloc] init];
	}
	
	if(ccrNotices == nil) {
		NSLog(@"Instantiating ccr notices dictionary.");
		ccrNotices = [[NSMutableDictionary alloc] init];
	}
	
	if(googlehealth == nil) {
		// googlehealth = [[GoogleHealth alloc] init];
		NSLog(@"ccrView 1: mProfileListFeed => %@", [googlehealth.mProfileListFeed description]);
		NSLog(@"ccrView 2: mProfileFeed => %@", [googlehealth.mProfileFeed description]);
	}
	
	[self.tableView reloadData];
	[super viewWillAppear:animated];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [myProfileList count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Set up the cell...
	NSUInteger row = [indexPath row];
	[cell.textLabel setText:[myProfileList objectAtIndex:row]];
    return cell;
}

// Once user selects a row, load what? recordViewController?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	NSEnumerator *keyEnum = [ccrProfiles keyEnumerator];
	NSString *key;
	BOOL profileNotFound = YES;
	NSUInteger row = [indexPath row];
	curSelectedProfile = [myProfileList objectAtIndex:row];
	NSLog(@"Profile for '%@' selected", curSelectedProfile);
	
	// if profile has already been added to dictionary then dont bother fetching
	// from google health
	if(ccrProfiles != nil) {
		// check 
		while( (key = [keyEnum nextObject]) != nil) {
			if(key == curSelectedProfile) {
				// NSMutableArray *entries = [ccrProfiles objectForKey:key];
				// NSLog(@"Found profile entry for '%@'", key);
				// printf("DEBUG: Entries = %i\n", [entries count]);
				profileNotFound = NO;
			}
		}
	}
	
	if(profileNotFound) {
		// attempt to fetch profile for the first time.
		[googlehealth.mProfileFeed release];
		googlehealth.mProfileFeed = nil;
		googlehealth.mRegisterFeed = nil;
		[self fetchSelectedRegisterFeeds:row];
		[self fetchSelectedProfile:row];
	}
	else {
		// found profile in ccrProfiles dictionary, just move on to the next controller?
		NSLog(@"Profile exists, will display record view controller now.");
		[self loadNextView];
	}
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (void)dealloc {
	[myProfileList release];
	[googlehealth release];
	[ccrProfiles release];
	[ccrNotices release];
	[curSelectedProfile release];
	[recordViewController release];
    [super dealloc];
}

#pragma mark -
#pragma mark Select Google Health profile

- (void)fetchSelectedRegisterFeeds: (int)rowIndex
{
	GDataEntryBase *profileListEntry = [self selectedProfileListEntry:rowIndex];
	if (profileListEntry != nil) {
		
		NSString *profileID = [[profileListEntry content] stringValue];
		
		GDataServiceGoogleHealth *service = [googlehealth healthService];
		
		NSURL *feedURL;
		// fetch notices in the register feed
		feedURL = [googlehealth.mServiceClass registerFeedURLForProfileID:profileID];
		[service fetchFeedWithURL:feedURL
						  delegate:self
				 didFinishSelector:@selector(registerFeedTicket:finishedWithFeed:error:)];	
		googlehealth.isRegisterFeedPending = YES;
	}
}

- (void)registerFeedTicket:(GDataServiceTicket *)ticket
		  finishedWithFeed:(GDataFeedHealthRegister *)feed
					 error:(NSError *)error {
	if(error == nil) {
		// NSLog(@"We got some notices?");
		googlehealth.mRegisterFeed = [feed retain];
		// NSLog(@"mRegisterFeed content: %@", [googlehealth.mRegisterFeed description]);
		googlehealth.isRegisterFeedPending = NO;
	}
	else {
		NSLog(@"Error while retreving notices: %@", [error description]);
	}
}

// entry method to retrieve profile	
- (void)fetchSelectedProfile: (int)rowIndex
{
	GDataEntryBase *profileListEntry = [self selectedProfileListEntry:rowIndex];
	if (profileListEntry != nil) {
		
		NSString *profileID = [[profileListEntry content] stringValue];
		
		GDataServiceGoogleHealth *service = [googlehealth healthService];
		
		NSURL *feedURL;
		//		if ([self isProfileSegmentSelected]) {
		// fetch a profile feed
		feedURL = [googlehealth.mServiceClass profileFeedURLForProfileID:profileID];
		[service fetchFeedWithURL:feedURL
						 delegate:self
				didFinishSelector:@selector(profileFeedTicket:finishedWithFeed:error:)];
	}
}	

// get the profileList selected in the top list, or nil if none
- (GDataEntryBase *)selectedProfileListEntry: (int)rowIndex {
	
	NSArray *profileLists = [googlehealth.mProfileListFeed entries];
	if ([profileLists count] > 0 && rowIndex > -1) {
		
		GDataEntryBase *profileList = [profileLists objectAtIndex:rowIndex];
		return profileList;
	}
	return nil;
}

// profiles/notices fetch callback
- (void)profileFeedTicket:(GDataServiceTicket *)ticket
         finishedWithFeed:(GDataFeedHealthProfile *)feed
                    error:(NSError *)error {
	if(error == nil) {
		googlehealth.mProfileFeed = [feed retain];
		NSLog(@"mProfileFeed set: %@\n", [googlehealth.mProfileFeed description]);
		// getting profile here from google health
		// but first, make sure we have notices.
		if(googlehealth.isRegisterFeedPending == NO) {
			// int notices = [[googlehealth.mRegisterFeed entries] count];	
			// printf("DEBUG: Number of notices: %i\n", notices);
			[self getNotices];
			[self getProfile];
			[self loadNextView];
		}
	}
	else {
		NSLog(@"ERROR: cannot retrieve profile => %@", error);
		// display UIAlert if login fails.
	}
}

// Assumes the profileFeedTicket callback has successfully set mProfileFeed
-(void) getProfile
{	
	// get profile entry 
	//NSArray *entries = [mProfileFeed entries];
	NSMutableArray *listCCREntries = [[NSMutableArray alloc] init];
	GDataEntryHealthProfile *profile;
	// GDataObject *xmlObject;
			
	int max = [[googlehealth.mProfileFeed entries] count];
	for(int i = 0; i < max; i++) {
		profile = [[googlehealth.mProfileFeed entries] objectAtIndex:i];
		[listCCREntries addObject:profile];
	}
	[ccrProfiles setObject:listCCREntries forKey:curSelectedProfile];
	[listCCREntries release];
}

-(void) getNotices
{
	NSMutableArray *listNotices = [[NSMutableArray alloc] init];
	GDataEntryHealthRegister *registryEntry;
	
	int max = [[googlehealth.mRegisterFeed entries] count];
	for(int i = 0; i < max; i++) {
		registryEntry = [[googlehealth.mRegisterFeed entries] objectAtIndex:i];
/*		NSLog(@"item => %@", [[registryEntry title] stringValue]);
		NSArray *authors = [registryEntry authors];
		for(int j = 0; j < [authors count]; j++) {
			NSString *email = [[authors objectAtIndex:j] email];
			NSString *auth = [[authors objectAtIndex:j] name];
			NSLog(@"authors => %@ %@", auth, email);
		}
		NSLog(@"date => %@", [registryEntry publishedDate]);
*/		
		[listNotices addObject:registryEntry];
	}
	[ccrNotices setObject:listNotices forKey:curSelectedProfile];
	[listNotices release];
}

#pragma mark -
#pragma mark Load View methods

// Loads the record view controller for a particular profile that belongs to patient.
// FOr example, 'Billy Bob => Notices, Demographics, Conditions, Medications, etc.'
-(void) loadNextView
{
	// Load right view controller here. 
	if(recordViewController == nil) {
		recordViewController = 
		[[RecordViewController alloc] initWithNibName:nil bundle:nil];
		// [[RecordViewController alloc] initWithStyle:UITableViewStyleGrouped];
	}
	recordViewController.ccrEntries = [ccrProfiles objectForKey:curSelectedProfile];	
	recordViewController.ccrNotices = [ccrNotices objectForKey:curSelectedProfile];
	recordViewController.googlehealth = googlehealth;
	recordViewController.title = curSelectedProfile;
	[self.navigationController pushViewController:recordViewController animated:YES];		
	
}

@end

